package org.zjx.strategy;

import org.zjx.core.IWindow;
import org.zjx.state.StateManager;
import org.zjx.strategy.impl.DefaultStrategy;
import org.zjx.strategy.impl.LoginStrategy;

import java.awt.image.BufferedImage;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 策略工厂
 */
public class StrategyFactory {
    private static StrategyFactory instance;
    private final Map<String, IStrategy> strategyMap = new HashMap<>();

    public StrategyFactory() {
        // 注册默认策略
        registerStrategy(new DefaultStrategy());
        registerStrategy(new LoginStrategy());
        System.out.println("[策略工厂] 初始化完成，已注册默认策略");
    }

    public static synchronized StrategyFactory getInstance() {
        if (instance == null) {
            instance = new StrategyFactory();
        }
        return instance;
    }

    /**
     * 注册策略
     */
    public void registerStrategy(IStrategy strategy) {
        strategyMap.put(strategy.getStrategyName(), strategy);
        System.out.println("[策略工厂] 注册策略: " + strategy.getStrategyName());
    }

    /**
     * 根据截图选择合适的策略并生成指令
     */
    public IStrategy selectAndExecuteStrategy(IWindow window, BufferedImage screenshot, StateManager stateManager) {
        if (screenshot == null) {
            System.err.println("[策略工厂] 截图为空，无法分析");
            return null;
        }

        // 获取所有策略并按优先级排序
        List<IStrategy> sortedStrategies = getAllStrategies();

        // 先进行快速预筛选
        List<IStrategy> candidateStrategies = sortedStrategies.stream()
                .filter(strategy -> strategy.isApplicable(window, screenshot, stateManager))
                .collect(Collectors.toList());

        // 然后按优先级深度检查
        for (IStrategy strategy : candidateStrategies) {
            if (strategy.isApplicable(window, screenshot, stateManager)) {
                System.out.println("[策略工厂] 选择策略: " + strategy.getStrategyName());
                return strategy;
            }
        }

        // 默认策略
        System.out.println("[策略工厂] 使用默认策略");
        return getDefaultStrategy();
    }

    /**
     * 获取特定策略
     */
    public IStrategy getStrategy(String name) {
        return strategyMap.get(name);
    }

    /**
     * 获取默认策略
     */
    public IStrategy getDefaultStrategy() {
        return strategyMap.get("DefaultStrategy");
    }

    /**
     * 获取所有策略（按优先级排序）
     */
    public List<IStrategy> getAllStrategies() {
        return strategyMap.values().stream()
                .sorted(Comparator.comparingInt(IStrategy::getPriority))
                .collect(Collectors.toList());
    }

    /**
     * 清空所有策略
     */
    public void clearStrategies() {
        strategyMap.clear();
        System.out.println("[策略工厂] 已清空所有策略");
    }

    /**
     * 获取策略数量
     */
    public int getStrategyCount() {
        return strategyMap.size();
    }
}